/*
 * 
 * Copyright 2010 David H Pollack
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 * 
 * 
 */

package com.dhpollack.rotogss.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.datanucleus.store.appengine.query.JDOCursorHelper;

import com.dhpollack.rotogss.data.YahooLeagueTeamStandingStats;
import com.dhpollack.rotogss.data.YahooLeagueTeamStandings;
import com.dhpollack.rotogss.helper.PMF;
import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

/**
 * @author davidpl
 *
 */
public class DeleteServlet extends HttpServlet {
	

	private PersistenceManager pm = PMF.get().getPersistenceManager();
	
	protected void service(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException {

		// This is going to update the timestamp of the standings entities
		// My next modification is going to add the league key to the standings entity
		// for filtering
		boolean callSelf = false;
		
		
		String lastCursorString = (String) req.getAttribute("cursor");
		
		Query query = pm.newQuery(YahooLeagueTeamStandings.class);
		query.setOrdering("leagueKey");
		if(lastCursorString != null) {
			log("Found Cursor: " + lastCursorString);
	        Cursor lastCursor = Cursor.fromWebSafeString(lastCursorString);
	        Map<String, Object> extensionMap = new HashMap<String, Object>();
	        extensionMap.put(JDOCursorHelper.CURSOR_EXTENSION, lastCursor);
	        query.setExtensions(extensionMap);
		} else {
			log("Didn't find cursor");
		}

		query.setRange(0, 100);
		List<YahooLeagueTeamStandings> results;
		try {
			results = (List<YahooLeagueTeamStandings>) query.execute();
			if(results.iterator().hasNext()) {
				for(YahooLeagueTeamStandings ylts : results) {
					//if(ylts.getTimestamp() == null) {
						//Update timestamp with below call
						//updateStandingTimestamp(ylts);
					//}
					//if(ylts.getLeagueKey() == null) {
						//updateStandingLeagueKey(ylts);
					//}
					if(ylts.getStatKeys().isEmpty()) {
						updateStats(ylts);
					}
				}
                callSelf = true;
			} else {
	            // ... no results ...
	        	log("No users found");
	        	callSelf = false;
	        	return;
	        }
		} finally {
	        query.closeAll();
	    }
		
	    if(callSelf) {
            Cursor currentCursor = JDOCursorHelper.getCursor(results);
            String currentCursorString = currentCursor.toWebSafeString();
	    	req.setAttribute("cursor", currentCursorString);
	    	
	    	log(currentCursorString);
	        req.getRequestDispatcher(req.getServletPath()).include(req, resp);
	    	
	    }


		
	}

	private void updateStandingLeagueKey(YahooLeagueTeamStandings ylts) {
		// TODO Auto-generated method stub
		Transaction tx = pm.currentTransaction();
		
		Key league_key = ylts.getStandingsKey().getParent().getParent();
		ylts.setLeagueKey(league_key);
		try {
			tx.begin();
			pm.makePersistent(ylts);
			log(ylts.getStandingsKey() + " to league: " + league_key);
			tx.commit();
		} finally {
			if(tx.isActive()) {
				tx.rollback();
			}
		}
		
		
	}
	private void updateStandingTimestamp(YahooLeagueTeamStandings ylts) {
		// TODO Auto-generated method stub
		Transaction tx = pm.currentTransaction();
		
		String league_update_timestamp = ylts.getStandingsKey().getName();
		Date d = new Date();
		d.setTime(Long.parseLong(league_update_timestamp) * 1000);
		ylts.setTimestamp(d);
		try {
			tx.begin();
			pm.makePersistent(ylts);
			log(ylts.getStandingsKey() + " to timestamp: " + d.toString());
			tx.commit();
		} finally {
			if(tx.isActive()) {
				tx.rollback();
			}
		}
		
	}
	
	private void updateStats(YahooLeagueTeamStandings ylts) {
		// TODO Auto-generated method stub
		Transaction tx = pm.currentTransaction();
		List<Key> stat_keys = new ArrayList<Key>();
		List<Double> stat_values = new ArrayList<Double>();
		Set<YahooLeagueTeamStandingStats> stats = ylts.getStandingsStats();
		for(YahooLeagueTeamStandingStats stat : stats) {
			stat_keys.add(stat.getStatkey());
			stat_values.add(stat.getStatvalue());
		}
		try {
			tx.begin();
			ylts.setStatKeys(stat_keys);
			ylts.setStatValues(stat_values);
			pm.makePersistent(ylts);
			log(ylts.getStandingsKey() + " to new stats list.");
			tx.commit();
		} finally {
			if(tx.isActive()) {
				tx.rollback();
			}
		}
		
	}

	
	/* This code was used to delete games tracked set from a specific user
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)

	protected void service(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException {
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		
		
		String user = req.getParameter("user");
		
		if(user == null) {
			log("No user set");
			return;
		}

		RotoGSSUsers rotogss_user;
		Key rotogss_userkey = new KeyFactory.Builder(RotoGSSUsers.class.getSimpleName(),user).getKey();
		try {
			tx.begin();
			try {
				rotogss_user = pm.getObjectById(RotoGSSUsers.class, rotogss_userkey);
				rotogss_user.setYahooGamesTracked(new LinkedHashSet<Key>());
				pm.makePersistent(rotogss_user);
			} catch(JDOObjectNotFoundException e) {
				log("No user found for " + user);
				log("Key used: " + rotogss_userkey.toString());
				return;
			}
			tx.commit();
		} finally {
			if(tx.isActive()) {
				tx.rollback();
			}
		}

	}

	*/

}
